package com.rongzhong.routing.hibernate;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.rongzhong.routing.util.Configuration;

/**
 * 
 * @author longxuegang@gmail.com
 * @version 1.0 2011-9-22
 * @since 1.0
 * @see
 */

public class HibernateUtil {

	private Configuration configure = Configuration.getInstance();
	private final int storageDBIndex = configure.getStorageDBIndex();
	private final int dbNumber = configure.getDatabaseNum();
	private Map<Integer,HibernateFactory> hibernatesMap = new HashMap<Integer, HibernateFactory>();
	private static Logger log = LoggerFactory.getLogger(HibernateUtil.class);
	private static HibernateUtil instance = new HibernateUtil();
	
	public static HibernateUtil getInstance(){
		return instance;
	}
	
	public HibernateUtil(){
		init();
	}
	
	private void init() {
		for (int dbIndex = 0; dbIndex < dbNumber; dbIndex++) {
			HibernateFactory factory = new HibernateFactory("config/hibernate_" + (dbIndex) + ".cfg.xml");
			hibernatesMap.put(dbIndex, factory);
		}
	}
	
	
	public Session currentSession(int dbIndex) {
		if (hibernatesMap.containsKey(dbIndex)) {
			return hibernatesMap.get(dbIndex).currentSession();
		}else {
			log.error("create session run into error");
			return null;
		}
	}
	
	public Session getStorageDBSession() {
		if (hibernatesMap.containsKey(storageDBIndex)) {
			return hibernatesMap.get(storageDBIndex).currentSession();
		}else {
			log.error("create session run into error");
			return null;
		}
	}

	public void closeSession(Session session) throws HibernateException {
		if (session != null){
			Iterator<Integer> ite = hibernatesMap.keySet().iterator();
			while (ite.hasNext()) {
				hibernatesMap.get(ite.next()).closeSession(session);
			}
		}
	}
}

